//
//  AccountManager.m
//  Module
//
//  Created by Fanty on 13-12-26.
//  Copyright (c) 2013年 Fanty. All rights reserved.
//

#import "AccountManager.h"

#import <MainModuleSDK/DataCenter.h>
#import "ApiConstant+Cube.h"
#import <chameleon-ios-sdk/CApplication.h>
#import <MainModuleSDK/MainModule.h>

#import <MainModuleSDK/AsyncTask.h>

#import "ASIFormDataRequest.h"
#import "RoleParser.h"

@interface AccountManager()
-(void)syncTimeEvent;
@end


@implementation AccountManager{
    NSTimer* timer;
    AsyncTask* task;
}

-(AsyncTask*)auth{
    MainModule* mainModule=(MainModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Main"];
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[[ApiConstant defaultConstant] authURL:[DataCenter defaultCenter].username]];
    request.timeOutSeconds=10.0f;
    [request setPersistentConnectionTimeoutSeconds:10.0f];
    
    RoleParser* parser=[[RoleParser alloc] init];
    return [mainModule asyncWithOperation:request parser:parser];
}

-(void)cancelSync{
    [timer invalidate];
    timer=nil;
    [task cancel];
    task=nil;
    
}

-(void)syncTimeEvent{
    [self cancelSync];
    if([[DataCenter defaultCenter].username length]>0){
        task=[self auth];
        __block AsyncTask* __task=task;
        __block AccountManager* objSelf=self;
        [task setFinishBlock:^{
            if([__task result]!=nil){
                [DataCenter defaultCenter].roles=[__task result];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"CubeAuthSync_Success" object:nil];
            }
            [objSelf syncAuth:NO];
        }];
    }
}

-(void)syncAuth:(BOOL)callNow{
    if(callNow){
        [self syncTimeEvent];
    }
    else{
        [self cancelSync];
        timer=[NSTimer scheduledTimerWithTimeInterval:300.0f target:self selector:@selector(syncTimeEvent) userInfo:nil repeats:NO];
        
    }
}



@end
